<?php

/**
 * edit a single book
 *
 * @author vbolshov
 */

include dirname(__FILE__) . '/../setup.php';

use bs\Book;
use bs\Author;
use bs\Renderer;

if ($id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT))
{
	$thebook = Book::find($id)->fetchOne();
} else {
	$thebook = new Book();
}

if ('POST' == $_SERVER['REQUEST_METHOD']) {
	$thebook->title = @$_POST['title'];
	$thebook->save();
	$thebook->setAuthors(filter_input(INPUT_POST, 'author', FILTER_VALIDATE_INT, array('flags' => FILTER_REQUIRE_ARRAY)));
	echo json_encode(array('code' => 'ok', 'data' => $thebook->toArray()));
	exit;
}

$view = Renderer::getView('editbook.php');
$view->book = $thebook;
$view->author_list = Author::findAll();
$view->render();